package com.zhiche.lisa.lspm.service.trailer.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.*;
import com.zhiche.lisa.core.enums.exception.CarrierEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.RegexUtil;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.lspm.config.LspmProperties;
import com.zhiche.lisa.lspm.dao.mapper.trailer.TrailerInfoMapper;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierCard;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierInfo;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierTrailerBind;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierTrailerBindLog;
import com.zhiche.lisa.lspm.dao.model.driver.*;
import com.zhiche.lisa.lspm.dao.model.fleet.Fleet;
import com.zhiche.lisa.lspm.dao.model.lsp.LspInfo;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerAuditLog;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerLicense;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerLicenseAttach;
import com.zhiche.lisa.lspm.dao.model.trailer.bo.*;
import com.zhiche.lisa.lspm.dto.CarrierToErpDTO;
import com.zhiche.lisa.lspm.dto.DriverToErpDTO;
import com.zhiche.lisa.lspm.dto.TrailerToErpDTO;
import com.zhiche.lisa.lspm.dto.VehicleDTO;
import com.zhiche.lisa.lspm.service.carrier.ICarrierCardService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierInfoService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierTrailerBindLogService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierTrailerBindService;
import com.zhiche.lisa.lspm.service.driver.*;
import com.zhiche.lisa.lspm.service.fleet.IFleetBindService;
import com.zhiche.lisa.lspm.service.fleet.IFleetService;
import com.zhiche.lisa.lspm.service.lsp.LspInfoService;
import com.zhiche.lisa.lspm.service.trailer.ITrailerAuditLogService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.trailer.TrailerLicenseAttachService;
import com.zhiche.lisa.lspm.service.trailer.TrailerLicenseService;
import com.zhiche.lisa.lspm.service.utils.DictionaryUtil;
import com.zhiche.lisa.lspm.service.utils.IntegrationUtil;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.common.AccountVO;
import com.zhiche.lisa.lspm.vo.common.LicenseTypeVo;
import com.zhiche.lisa.lspm.vo.common.TransportationTypeVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetBindVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetLineVO;
import com.zhiche.lisa.lspm.vo.vehicle.TrailerBasicVO;
import com.zhiche.lisa.lspm.vo.vehicle.TrailerDetailVO;
import com.zhiche.lisa.lspm.vo.vehicle.TrailerInfoLineVO;
import com.zhiche.lisa.lspm.vo.vehicle.WeChatVehicle;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 挂车 service impl
 *
 * @author lbl
 * @since 2018-05-28
 */
@Service
public class TrailerInfoServiceImpl extends ServiceImpl<TrailerInfoMapper, TrailerInfo> implements TrailerInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TrailerInfoServiceImpl.class);

    @Autowired
    private TrailerLicenseService trailerLicenseService;
    @Autowired
    private TrailerLicenseAttachService trailerLicenseAttachService;
    @Autowired
    private LspInfoService lspInfoService;
    @Autowired
    private ITrailerAuditLogService iTrailerAuditLogService;
    @Autowired
    private ICarrierTrailerBindService carrierTrailerBindService;
    @Autowired
    private ICarrierInfoService carrierInfoService;
    @Autowired
    private ICarrierTrailerBindLogService carrierTrailerBindLogService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private MdmUtil mdmUtil;
    @Autowired
    private IDriverCarrierBindService driverCarrierBindService;
    @Autowired
    private UaaUtil uaaUtil;
    @Autowired
    private IDriverCarrierBindLogService driverCarrierBindLogService;
    @Autowired
    private IFleetBindService fleetBindService;
    @Autowired
    private IDriverLicenseService driverLicenseService;
    @Autowired
    private IntegrationUtil integrationUtil;
    @Autowired
    private ICarrierCardService cardService;
    @Autowired
    private TrailerInfoService trailerInfoService;
    @Autowired
    private IFleetService fleetService;
    @Autowired
    private LspmProperties properties;
    @Autowired
    private IDriverCheckinService driverCheckinService;


    @Value("${lisa.tms.driverWaybillUrl}")
    private String driverWaybillUrl;
    @Value("${uaa.updateTenantOfAccountUrl}")
    private String updateTenantOfAccountUrl;
    @Value("${uaa.url}")
    private String uuaUrl;
    @Value("${uaa.socketTimeout}")
    private Integer socketTimeout;
    @Value("${integrationToOtm}")
    private String integrationToOtm;
    @Value("${integration.url}")
    private String integrationUrl;
    @Value("${integration.trailerPushErpUrl}")
    private String trailerPushErpUrl;
    @Value("${integration.carrierPushErpUrl}")
    private String carrierPushErpUrl;
    @Value("${integration.driverPushErpUrl}")
    private String driverPushErpUrl;
    @Value("${uaa.url}")
    private String uaaUrl;
    @Value("${logRedis.isTest}")
    private boolean isTest;

    @Override
    public Page<TrailerInfoLineVO> trailerInfoLine(Page<TrailerInfoLineBO> page, String authorization) {
        EntityWrapper<TrailerInfoLineBO> ew = trailerInfoLineWhere(page);
        Page<TrailerInfoLineVO> pageVo = new Page<>();
        List<TrailerInfoLineVO> list = baseMapper.trailerInfoLine(page, ew);
        list.forEach(trailerInfoLineVO -> {
            AccountVO accountVO = uaaUtil.getAccountById(trailerInfoLineVO.getCreator(), authorization);
            if (Objects.nonNull(accountVO)) {
                trailerInfoLineVO.setCreator(accountVO.getIdentifier());
            }
        });
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(list);
        return pageVo;
    }

    @Override
    public Page<TrailerInfoLineVO> authedTrailerInfoLine(Page<TrailerInfoLineBO> page) {
        EntityWrapper<TrailerInfoLineBO> ew = trailerInfoLineWhere(page);
        Page<TrailerInfoLineVO> pageVo = new Page<>();
        List<TrailerInfoLineVO> list = baseMapper.authedTrailerInfoLine(page, ew);
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(list);
        return pageVo;
    }

    private EntityWrapper<TrailerInfoLineBO> trailerInfoLineWhere(Page<TrailerInfoLineBO> page) {
        EntityWrapper<TrailerInfoLineBO> ew = new EntityWrapper<>();
        // 挂车车牌
        if (page.getCondition() != null
                && !StringUtils.isEmpty(page.getCondition().get("plate"))) {
            ew.like("plate", page.getCondition().get("plate").toString().trim());
        }
        // 承运商 id
        if (page.getCondition() != null
                && !StringUtils.isEmpty(page.getCondition().get("lspId"))) {
            ew.eq("lsp_id", page.getCondition().get("lspId").toString().trim());
        }
        if (page.getCondition() != null
                && !StringUtils.isEmpty(page.getCondition().get("canDel"))) {
            ew.eq("is_delete", page.getCondition().get("canDel").toString().trim());
        } else {
            ew.eq("is_delete", 0);
        }
        if (page.getCondition() != null
                && Objects.nonNull(page.getCondition().get("tenantId"))) {
            ew.eq("tenant_id", page.getCondition().get("tenantId").toString().trim());
        }
        ew.orderBy("gmt_create", false);
        return ew;
    }

    public void checkModifyData(ModifyTrailerInfoBO modifyTrailerInfoBO, String operate) {
        if (modifyTrailerInfoBO == null || StringUtils.isEmpty(operate))
            return;
        if (operate.equals("modify")) {
            if (modifyTrailerInfoBO.getId() == null)
                return;
            Wrapper<TrailerInfo> plateTrailerEntity = new EntityWrapper<>();
            plateTrailerEntity.eq("plate", modifyTrailerInfoBO.getPlate().trim()).ne("id", modifyTrailerInfoBO.getId());
            List<TrailerInfo> plateTrailerList = baseMapper.selectTrailerNoTenant(plateTrailerEntity);
            if (!CollectionUtils.isEmpty(plateTrailerList)) {
                throw new BaseException(CarrierEnum.PLATE_EXIST.getCode(), "该车牌号已被使用");
            }
        }
        if (modifyTrailerInfoBO.getPlate() == null)
            return;
        if (operate.equals("insert")) {
            Wrapper<TrailerInfo> plateTrailerEntity = new EntityWrapper<>();
            plateTrailerEntity.eq("plate", modifyTrailerInfoBO.getPlate().trim());
            List<TrailerInfo> plateTrailerList = baseMapper.selectTrailerNoTenant(plateTrailerEntity);
            if (!CollectionUtils.isEmpty(plateTrailerList)) {
                throw new BaseException(CarrierEnum.PLATE_EXIST.getCode(), "该车牌号已被使用");
            }
        }
    }

    @Transactional
    @Override
    public void addTrailerInfo(ModifyTrailerInfoBO modifyTrailerInfoBO) {
        try {
            TrailerInfo trailerInfo = new TrailerInfo();
            if (Objects.isNull(modifyTrailerInfoBO.getTenantId())) throw new BaseException("请选择所属公司");
            checkModifyData(modifyTrailerInfoBO, "insert");
            if (!Strings.isNullOrEmpty(modifyTrailerInfoBO.getOwnerName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyTrailerInfoBO.getOwnerName()))
                    throw new BaseException("车主姓名不合法");
            if (!Strings.isNullOrEmpty(modifyTrailerInfoBO.getManufacturer()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyTrailerInfoBO.getManufacturer()))
                    throw new BaseException("生产厂商不合法");
            if (!Strings.isNullOrEmpty(modifyTrailerInfoBO.getModel()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyTrailerInfoBO.getModel()))
                    throw new BaseException("品牌车型不合法");
            // 添加挂车基础信息
            Long lspId = lspInfoService.getLspIdByTenantId(modifyTrailerInfoBO.getTenantId());
            if (!Objects.isNull(lspId)) modifyTrailerInfoBO.setLspId(lspId);
            BeanUtils.copyProperties(modifyTrailerInfoBO, trailerInfo);
            trailerInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
            trailerInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
            trailerInfo.setCreateFrom(SourceEnum.LSPM.getText());
            this.insert(trailerInfo);
            // 添加挂车证照
            List<ModifyTrailerLicenseBO> modifyCarrierLicenseBOList = modifyTrailerInfoBO.getModifyTrailerLicenseBOList();
            for (ModifyTrailerLicenseBO modifyTrailerLicenseBO : modifyCarrierLicenseBOList) {
                TrailerLicense trailerLicense = new TrailerLicense();
                BeanUtils.copyProperties(modifyTrailerLicenseBO, trailerLicense);
                trailerLicense.setTrailerId(trailerInfo.getId());
                trailerLicenseService.insert(trailerLicense);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception ex) {
            throw new BaseException(-1, "操作异常请重试");
        }

    }

    private TrailerLicense getLicenseByIdOrType(ModifyTrailerLicenseBO modifyTrailerLicenseBO, Long trailerId) {
        TrailerLicense license = new TrailerLicense();
        if (Objects.isNull(modifyTrailerLicenseBO.getId())) {
            EntityWrapper<TrailerLicense> ew = new EntityWrapper<>();
            ew.eq("trailer_id", trailerId);
            ew.eq("license_type_id", modifyTrailerLicenseBO.getLicenseTypeId());
            List<TrailerLicense> trailerLicenses = trailerLicenseService.selectList(ew);
            if (!CollectionUtils.isEmpty(trailerLicenses)) {
                license = trailerLicenses.get(0);
            }
        } else {
            EntityWrapper<TrailerLicense> ew = new EntityWrapper<>();
            ew.eq("id", modifyTrailerLicenseBO.getId());
            List<TrailerLicense> trailerLicenses = trailerLicenseService.selectList(ew);
            if (!CollectionUtils.isEmpty(trailerLicenses)) {
                license = trailerLicenses.get(0);
            }
        }
        return license;
    }

    @Override
    public void updateLicense(ModifyTrailerInfoBO modifyTrailerInfoBO) {
        if (Objects.isNull(modifyTrailerInfoBO.getId())) throw new BaseException("未绑定承运商");
        List<ModifyTrailerLicenseBO> toTrailerLicenseList = modifyTrailerInfoBO.getModifyTrailerLicenseBOList();
        toTrailerLicenseList.forEach(modifyTrailerLicenseBO -> {
            TrailerLicense license = new TrailerLicense();
            BeanUtils.copyProperties(modifyTrailerLicenseBO, license);
            license.setId(getLicenseByIdOrType(modifyTrailerLicenseBO, modifyTrailerInfoBO.getId()).getId());
            if (Objects.isNull(license.getId())) {
                license.setTrailerId(modifyTrailerInfoBO.getId());
                trailerLicenseService.insert(license);
                // 添加承运商证照附件
                List<TrailerLicenseAttach> trailerLicenseAttaches = modifyTrailerLicenseBO.getTrailerLicenseAttachList();
                for (TrailerLicenseAttach trailerLicenseAttache :
                        trailerLicenseAttaches) {
                    trailerLicenseAttache.setTrailerId(modifyTrailerInfoBO.getId());
                    trailerLicenseAttache.setLicenseId(license.getId());
                }
                if (!CollectionUtils.isEmpty(trailerLicenseAttaches))
                    trailerLicenseAttachService.insertBatch(trailerLicenseAttaches);
            } else {
                for (TrailerLicenseAttach trailerLicenseAttach :
                        modifyTrailerLicenseBO.getTrailerLicenseAttachList()) {
                    //删除原有附件
                    EntityWrapper<TrailerLicenseAttach> ewAttach = new EntityWrapper<>();
                    ewAttach.eq("trailer_id", modifyTrailerInfoBO.getId());
                    ewAttach.eq("license_id", license.getId());
                    ewAttach.eq("attach_type", trailerLicenseAttach.getAttachType());
                    //获取对应挂车现有证照的附件信息
                    TrailerLicenseAttach licenseAttach = trailerLicenseAttachService.selectOne(ewAttach);
                    //若存在附件
                    if (Objects.nonNull(licenseAttach)) {
                        //和本次上传的附件不一样，软删之后在新增，不一样直接跳过本次新增
                        if (!trailerLicenseAttach.getAttachKey().equals(licenseAttach.getAttachKey())) {
                            trailerLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
                        } else {
                            continue;
                        }
                    }
                    //修改附件对应信息，写入库
                    trailerLicenseAttach.setTrailerId(modifyTrailerInfoBO.getId());
                    trailerLicenseAttach.setLicenseId(license.getId());
                    trailerLicenseAttachService.insert(trailerLicenseAttach);
                }
            }
        });
    }

    @Override
    public void deleteLicense(ModifyTrailerLicenseBO modifyTrailerLicenseBO) {
        for (TrailerLicenseAttach trailerLicenseAttach :
                modifyTrailerLicenseBO.getTrailerLicenseAttachList()) {
            if (Objects.isNull(trailerLicenseAttach.getId())) {
                EntityWrapper<TrailerLicense> ew = new EntityWrapper<>();
                ew.eq("license_type_id", modifyTrailerLicenseBO.getLicenseTypeId());
                ew.eq("trailer_id", modifyTrailerLicenseBO.getTrailerId());
                List<TrailerLicense> trailerLicenses = trailerLicenseService.selectList(ew);
                if (CollectionUtils.isEmpty(trailerLicenses)) throw new BaseException("未查找到匹配删除项");
                EntityWrapper<TrailerLicenseAttach> ewAttach = new EntityWrapper<>();
                TrailerLicense trailerLicense = trailerLicenses.get(0);
                ewAttach.eq("trailer_id", modifyTrailerLicenseBO.getTrailerId());
                ewAttach.eq("license_id", trailerLicense.getId());
                ewAttach.eq("attach_type", trailerLicenseAttach.getAttachType());
                TrailerLicenseAttach licenseAttach = trailerLicenseAttachService.selectOne(ewAttach);
                if (Objects.nonNull(licenseAttach)) {
                    trailerLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
                }
                trailerLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
            } else {
                EntityWrapper<TrailerLicenseAttach> ewAttach = new EntityWrapper<>();
                ewAttach.eq("id", trailerLicenseAttach.getId());
                TrailerLicenseAttach licenseAttach = trailerLicenseAttachService.selectOne(ewAttach);
                if (Objects.nonNull(licenseAttach)) {
                    trailerLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
                }
            }
        }
    }

    @Override
    public ModifyTrailerInfoBO findModifyInfo(Long id) {

        if (id == null)
            return null;

        // 查询编辑承运商信息
        TrailerInfo trailerInfo = this.selectById(id);
        if (trailerInfo == null)
            return null;

        ModifyTrailerInfoBO modifyTrailerInfoBO = new ModifyTrailerInfoBO();

        BeanUtils.copyProperties(trailerInfo, modifyTrailerInfoBO);

        // 查询所属承运商
        if (modifyTrailerInfoBO.getLspId() != null) {
            LspInfo lspInfo = lspInfoService.selectById(modifyTrailerInfoBO.getLspId());
            if (lspInfo != null) {
                modifyTrailerInfoBO.setLspName(lspInfo.getName());
            }
        }

        //是否存在附件
        Boolean isHaveAttach = false;

        // 查找牵引车的证照信息
        Wrapper<TrailerLicense> licenseEntity = new EntityWrapper<>();
        licenseEntity.eq("trailer_id", id);
        List<TrailerLicense> licenseList = trailerLicenseService.selectList(licenseEntity);
        if (!CollectionUtils.isEmpty(licenseList)) {
            List<ModifyTrailerLicenseBO> modifyTrailerLicenseBOList = new ArrayList<>();
            for (TrailerLicense license : licenseList) {
                ModifyTrailerLicenseBO modifyTrailerLicenseBO = new ModifyTrailerLicenseBO();
                BeanUtils.copyProperties(license, modifyTrailerLicenseBO);


                // 查找证照的附件信息
                Wrapper<TrailerLicenseAttach> licenseAttachEntity = new EntityWrapper<>();
                licenseAttachEntity.eq("license_id", license.getId()).eq("trailer_id", id);
                List<TrailerLicenseAttach> trailerLicenseAttachList = trailerLicenseAttachService.selectList(licenseAttachEntity);
                if (!CollectionUtils.isEmpty(trailerLicenseAttachList)) {
                    modifyTrailerLicenseBO.setTrailerLicenseAttachList(trailerLicenseAttachList);
                    isHaveAttach = true;
                }

                modifyTrailerLicenseBO.setStatus(getValidStatus(license, isHaveAttach));

                modifyTrailerLicenseBOList.add(modifyTrailerLicenseBO);
            }
            if (!CollectionUtils.isEmpty(modifyTrailerLicenseBOList)) {
                modifyTrailerInfoBO.setModifyTrailerLicenseBOList(modifyTrailerLicenseBOList);
            }
        }
        return modifyTrailerInfoBO;
    }

    @Override
    public void modifyTrailerInfo(ModifyTrailerInfoBO modifyTrailerInfoBO) {

        try {
            if (Objects.isNull(modifyTrailerInfoBO.getTenantId())) throw new BaseException("请选择所属公司");
            checkModifyData(modifyTrailerInfoBO, "modify");
            if (!Strings.isNullOrEmpty(modifyTrailerInfoBO.getOwnerName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyTrailerInfoBO.getOwnerName()))
                    throw new BaseException("车主姓名不合法");
            if (!Strings.isNullOrEmpty(modifyTrailerInfoBO.getManufacturer()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyTrailerInfoBO.getManufacturer()))
                    throw new BaseException("生产厂商不合法");
            if (!Strings.isNullOrEmpty(modifyTrailerInfoBO.getModel()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyTrailerInfoBO.getModel()))
                    throw new BaseException("品牌车型不合法");
            // 更新挂车基础信息
            TrailerInfo trailerInfo = new TrailerInfo();
            BeanUtils.copyProperties(modifyTrailerInfoBO, trailerInfo);
            Long lspId = lspInfoService.getLspIdByTenantId(modifyTrailerInfoBO.getTenantId());
            trailerInfo.setLspId(lspId);
            if (!Objects.isNull(trailerInfo)) {
                Integer authStatus = trailerInfo.getAuthStatus();
                if (authStatus == AuthStatusEnum.CERTIFICATION.getCode()) {
                    throw new BaseException(-1, "该挂车已经认证，请取消认证后再进行修改");
                }
            }

            this.updateById(trailerInfo);

            // 查询挂车下的证照
            Wrapper<TrailerLicense> trailerLicenseEntity = new EntityWrapper<>();
            trailerLicenseEntity.eq("trailer_id", trailerInfo.getId());
            List<TrailerLicense> selectTrailerLicenseList = trailerLicenseService.selectList(trailerLicenseEntity);

            // 前端传送的证照
            List<ModifyTrailerLicenseBO> toTrailerLicenseList = modifyTrailerInfoBO.getModifyTrailerLicenseBOList();
//
            if (CollectionUtils.isEmpty(selectTrailerLicenseList)) {
                //原来没有证照
                toTrailerLicenseList.forEach(modifyTrailerLicenseBO -> {
                    TrailerLicense trailerLicense = new TrailerLicense();
                    BeanUtils.copyProperties(modifyTrailerLicenseBO, trailerLicense);
                    trailerLicense.setTrailerId(trailerInfo.getId());
                    trailerLicenseService.insert(trailerLicense);
                });
            } else {
                toTrailerLicenseList.forEach(modifyTrailerLicenseBO -> {
                    TrailerLicense license = new TrailerLicense();
                    BeanUtils.copyProperties(modifyTrailerLicenseBO, license);
                    license.setId(getLicenseByIdOrType(modifyTrailerLicenseBO, modifyTrailerInfoBO.getId()).getId());
                    if (Objects.isNull(license.getId())) {
                        //新增
                        license.setTrailerId(trailerInfo.getId());
                        trailerLicenseService.insert(license);
                    } else {
                        //更新
                        trailerLicenseService.updateById(license);
                    }
                });
            }

        } catch (BaseException e) {
            throw e;
        } catch (Exception ex) {
            throw new BaseException(-1, "操作异常请重试");
        }
    }


    @Override
    public Page<TrailerDetailVO> getTrailerByLsp(Page<TrailerDetailVO> page, String authorization) {
        Wrapper<TrailerInfo> ew = new EntityWrapper<>();
        if (Objects.isNull(page.getCondition().get("lspId")) || Strings.isNullOrEmpty(page.getCondition().get("lspId").toString()))
            throw new BaseException("未获取到对应承运商");
        Long lspId = Long.parseLong(page.getCondition().get("lspId").toString());
        ew.eq("lsp_id", lspId);
        if (Objects.nonNull(page.getCondition().get("plate"))) {
            ew.like("plate", page.getCondition().get("plate").toString());
        }
        if (!Objects.isNull(page.getCondition().get("isAuth"))) {
            if ("1".equals(page.getCondition().get("isAuth").toString())) {
                ew.eq("auth_status", AuthStatusEnum.CERTIFICATION.getCode());
            } else {
                ew.eq("auth_status", AuthStatusEnum.UNAUTHORIZED.getCode());
            }
        }
        ew.eq("is_delete",TableStatusEnum.STATUS_0.getCode());
        Page<TrailerInfo> trailerInfoList = new Page<>(page.getCurrent(), page.getSize());
        trailerInfoList = this.selectPage(trailerInfoList, ew);
        BeanUtils.copyProperties(trailerInfoList, page);
        if (!CollectionUtils.isEmpty(trailerInfoList.getRecords())) {
            LspInfo lspInfo = lspInfoService.selectById(lspId);
            List<TrailerDetailVO> trailerDetailVOList = new ArrayList<>();
            for (TrailerInfo trailerInfo : trailerInfoList.getRecords()) {
                TrailerDetailVO trailerDetailVO = new TrailerDetailVO();
                BeanUtils.copyProperties(trailerInfo, trailerDetailVO);
                if (lspInfo != null) {
                    trailerDetailVO.setLspName(lspInfo.getName());
                }
                if (!Strings.isNullOrEmpty(trailerDetailVO.getCreator())) {
                    AccountVO accountVO = uaaUtil.getAccountById(trailerDetailVO.getCreator(), authorization);
                    if (Objects.nonNull(accountVO)) {
                        trailerDetailVO.setCreator(accountVO.getIdentifier());
                    }
                }
                trailerDetailVOList.add(trailerDetailVO);
                page.setRecords(trailerDetailVOList);
            }
        }
        return page;
    }
//    @Override
//    public CarrierTrailerVO getTrailerByLsp(Long driverId, String plate) {
//        CarrierTrailerVO carrierTrailerVO = new CarrierTrailerVO();
//        Wrapper<CarrierInfo> ew = new EntityWrapper<>();
//        ew.eq("plate", plate);
//        CarrierInfo carrierInfo = carrierInfoService.selectOne(ew);
//        if (Objects.isNull(carrierInfo)) return carrierTrailerVO;
//        carrierTrailerVO.setCarrierInfo(carrierInfo);
//        DriverCarrierBind driverCarrierBind = driverCarrierBindService.getCarrierBindByCarIdAndDriId(carrierInfo.getId(), driverId);
//        if (Objects.isNull(driverCarrierBind)) throw new BaseException("选定司机未与该牵引车绑定");
//        Wrapper<CarrierTrailerBind> ewCTBind = new EntityWrapper<>();
//        ewCTBind.eq("carrier_id", carrierInfo.getId());
//        List<CarrierTrailerBind> carrierTrailerBinds = carrierTrailerBindService.selectList(ewCTBind);
//        if (!CollectionUtils.isEmpty(carrierTrailerBinds)) {
//            TrailerInfo trailerInfo = new TrailerInfo();
//            trailerInfo.setId(carrierTrailerBinds.get(0).getTrailerId());
//        }
//        return carrierTrailerVO;
//    }

    @Transactional
    @Override
    public List<String> discontinuatTrailer(Long[] trailerIds) throws BaseException {
        List<String> msgs = Lists.newArrayList();
        if (ArrayUtils.isEmpty(trailerIds)) {
            throw new BaseException("挂车的ID为空");
        }
        for (Long id : trailerIds) {
            TrailerInfo trailerInfo = this.selectById(id);
            if (StatusEnum.DISCONTINUAT.getCode().equals(trailerInfo.getStatus())) {
                msgs.add("挂车:" + trailerInfo.getPlate() + ":已处于停用状态");
                continue;
            }
            // 2018-09-07 linbao 修改停用挂车没有成功
            trailerInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
            trailerInfo.updateById();
            //baseMapper.updateStatus(StatusEnum.DISCONTINUAT.getCode(), id);
        }
        return msgs;
    }

    @Transactional
    @Override
    public List<String> enableTrailer(Long[] trailerIds) throws BaseException {
        List<String> msgs = Lists.newArrayList();
        if (ArrayUtils.isEmpty(trailerIds)) {
            throw new BaseException("挂车的ID为空");
        }
        for (Long id : trailerIds) {
            TrailerInfo trailerInfo = this.selectById(id);
            if (StatusEnum.ENABLE.getCode().equals(trailerInfo.getStatus())) {
                msgs.add("挂车:" + trailerInfo.getPlate() + ":已处于启用状态");
                continue;
            }

            if (AuthStatusEnum.UNAUTHORIZED.getCode().equals(trailerInfo.getAuthStatus())) {
                msgs.add("挂车:" + trailerInfo.getPlate() + ":未认证,无法启用");
                continue;
            }
            // 2018-09-07 linbao 启用挂车修复
            trailerInfo.setStatus(StatusEnum.ENABLE.getCode());
            trailerInfo.updateById();
            //baseMapper.updateStatus(StatusEnum.ENABLE.getCode(), id);
        }
        return msgs;
    }

    @Override
    public void batchUpdateStatusByLspId(Integer authStatus, Integer status, List<Long> lspIdList) {
        baseMapper.batchUpdateStatusByLspId(authStatus, status, lspIdList);
    }

    @Override
    public List<TrailerInfo> getListsByLspId(Long lspId) {
        EntityWrapper<TrailerInfo> ew = new EntityWrapper<>();
        ew.where("lsp_id = {0}", lspId);
        List<TrailerInfo> list = this.selectList(ew);
        return list;
    }

    @Transactional
    public void trailerAuth(Long trailerId, String authorization) throws BaseException {
        TrailerInfo needAuthTrailer = this.selectById(trailerId);
        if (Objects.isNull(needAuthTrailer)) {
            throw new BaseException("挂车不存在");
        }
        if (needAuthTrailer.getAuthStatus().equals(AuthStatusEnum.CERTIFICATION.getCode())) {
            throw new BaseException("挂车:" + needAuthTrailer.getPlate() + ":" + "已经是认证状态，无需重复进行认证");
        }
        // 中联添加的挂车推erp
        authTrailerToERP(trailerId, authorization);

        TrailerInfo authTrailer = new TrailerInfo();
        authTrailer.setId(needAuthTrailer.getId());
        authTrailer.setAuthStatus(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
        authTrailer.setStatus(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
        authTrailer.setGmtUpdate(new Date());
        trailerInfoService.updateById(authTrailer);

        // fix 推送挂车类型
        WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(null, trailerId);
        trailerInfoToOTM(authorization, weChatVehicle);

        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        TrailerAuditLog trailerAuditLog = new TrailerAuditLog();
        BeanUtils.copyProperties(needAuthTrailer, trailerAuditLog);
        trailerAuditLog.setTrailerId(trailerId);
        if (Objects.nonNull(jwtAccountVO)) {
            trailerAuditLog.setTenantId(Long.parseLong(jwtAccountVO.getTenantId()));
            trailerAuditLog.setCreator(jwtAccountVO.getAccountId());
        }
        trailerAuditLog.setAuditResult(1);
        iTrailerAuditLogService.insert(trailerAuditLog);
    }

    public void trailerInfoToOTM(String authorization, WeChatVehicle weChatVehicle) {
        if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
            if (Objects.nonNull(weChatVehicle)
                    && weChatVehicle.getAuthStatus() == 1
                    && !StringUtils.isEmpty(weChatVehicle.getPlate())
                    && weChatVehicle.getTrailerAuthStatus() == 1) {
                //获取中联下面的所有管理员账号
                //List<AccountVO> listTenantAccount = uaaUtil.getListTenantAccount(1L, authorization);
                //List<Long> accountIds = new ArrayList<>();
                //for (AccountVO accountVO : listTenantAccount) {
                //    accountIds.add(Long.valueOf(accountVO.getId()));
                //}
                EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
                ew.eq("resource_id", weChatVehicle.getId())
                        .eq("resource_type", TableStatusEnum.STATUS_02.getCode())
                        //.in("creator", accountIds)
                        .orderBy("id", false);

                List<FleetBindVO> fleetCarrierVOS = fleetBindService.queryBindTrailerList(ew);

                VehicleDTO vehicleDTO = new VehicleDTO();
                // 设置车队类型-自有
                carrierInfoService.toOtmSetFleetType(null,weChatVehicle.getTrailerId(),weChatVehicle);
                BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
                if (!CollectionUtils.isEmpty(fleetCarrierVOS)) {
                    vehicleDTO.setFleetId(fleetCarrierVOS.get(0).getFleetId());
                } else {
                    vehicleDTO.setFleetId(weChatVehicle.getLspId());
                }
                if (!StringUtils.isEmpty(weChatVehicle.getTrailerTypeId())) {
                    String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicle.getTrailerTypeId()).getValue();
                    weChatVehicle.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
                }

                vehicleDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
                vehicleDTO.setVehicleProper(weChatVehicle.getTrailerProper());
                vehicleDTO.setTrailerTypeName(weChatVehicle.getTrailerTypeName());
                integrationUtil.exportVehicleToOTM(vehicleDTO);
            }
        }
    }

    @Override
    public void authTrailerToERP(Long trailerId, String authorization) {

        if (TableStatusEnum.STATUS_Y.getCode().equals(properties.getPushDataToERP())) {
            if (trailerId != null) {
                TrailerInfo trailer = baseMapper.selectByIdNoTenant(trailerId);
                List<NameValuePair> headNamePairs = Lists.newArrayList();
                headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
                //推送挂车
                TrailerToErpDTO trailerToErpDTO = new TrailerToErpDTO();
                trailerToErpDTO.setId(trailer.getId());
                trailerToErpDTO.setTrailerPlate(trailer.getPlate());
                trailerToErpDTO.setAxisNumber(trailer.getAxisNumber());
                String paramJson = JSONObject.toJSONString(trailerToErpDTO);
                LOGGER.info("TrailerToErp url: {},param:{} ", integrationUrl + trailerPushErpUrl, paramJson);
                String result = null;
                try {
                    RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"trailer"+trailerToErpDTO.getId(), JSON.toJSONString(trailerToErpDTO),"/erp-api/trailerPushErp",1,1,null,isTest);
                    result = HttpClientUtil.postJson(integrationUrl + trailerPushErpUrl, headNamePairs, paramJson, socketTimeout);
                    LOGGER.info("TrailerToErp result {} ", result);
                } catch (Exception e) {
                    LOGGER.error("TrailerToErp 超时失败  error:{} ", e);
                }
                if (StringUtils.isEmpty(result)) {
                    LOGGER.error("TrailerToErp 响应为空  param:{} ", paramJson);
                }
            }
        }
    }

    @Override
    public List<String> batchUpdateAuthStatusByIds(Long[] trailerIds, String authorization) throws BaseException {

        if (ArrayUtils.isEmpty(trailerIds)) {
            throw new BaseException("挂车的ID为空");
        }

        List<String> errorMsg = new ArrayList<>();

        for (Long trailerId : trailerIds) {
            try {
                trailerAuth(trailerId, authorization);
            } catch (BaseException e) {
                errorMsg.add(e.getMessage());
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                errorMsg.add("系统异常");
            }
        }
        return errorMsg;
    }

    private boolean licenseValid(Long trailerId) throws BaseException {

        EntityWrapper<TrailerLicense> ew = new EntityWrapper<>();
        ew.eq("trailer_id", trailerId);
        List<TrailerLicense> licenses = trailerLicenseService.selectList(ew);
        List<LicenseTypeVo> licenseTypes = mdmUtil.listLicenseTypeBySubject("04");
        for (TrailerLicense license : licenses) {
            LicenseTypeVo licenseType = getLicenseType(license.getLicenseTypeId(), licenseTypes);
            if (Objects.nonNull(licenseType)) {
                if (StringUtils.isEmpty(license.getLicenseId())) throw new BaseException(
                        licenseType.getTypeValue() + "编码为空");
//                if (Objects.isNull(license.getGmtReg())) throw new BaseException(licenseType.getTypeValue()
//                        + "生效日期为空");
//                if (!licenseType.getIsPerm().equals(1) && Objects.isNull(license.getGmtOverdue())) {
//                    throw new BaseException(licenseType.getTypeValue() + "失效日期为空！");
//                }
                Wrapper<TrailerLicenseAttach> ewAttach = new EntityWrapper<>();
                ewAttach.eq("license_id", license.getId()).and().eq("trailer_id", license.getTrailerId());
                if (trailerLicenseAttachService.selectCount(ewAttach) == 0) {
                    throw new BaseException(licenseType.getTypeValue() + "附件为空！");
                }
            } else {
                throw new BaseException("挂车证照类型有误");
            }

        }
        return true;
    }

    private LicenseTypeVo getLicenseType(Long licenseTypeId, List<LicenseTypeVo> licenseTypes) {
        LicenseTypeVo newLicenseType = null;
        Optional<LicenseTypeVo> optional = licenseTypes.stream().filter(licenseType -> licenseType.getId().equals(licenseTypeId)).findFirst();
        if (optional.isPresent()) {
            newLicenseType = optional.get();
        }
        return newLicenseType;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void batchUpdateCancelAuthStatusByIds(Long[] trailerIds) throws BaseException {
        try {
            if (ArrayUtils.isEmpty(trailerIds)) {
                throw new BaseException("挂车的ID为空");
            }
            List<Long> idList = Arrays.asList(trailerIds);
            idList.forEach(trailId -> {
                TrailerInfo trailerInfo = this.selectById(trailId);
                if (!Objects.isNull(trailerInfo)) {
                    if (trailerInfo.getAuthStatus() == AuthStatusEnum.UNAUTHORIZED.getCode()) {
                        throw new BaseException("挂车车牌号：" + trailerInfo.getPlate() + "已经取消认证，无需重复取消认证");
                    }
                }
            });
            baseMapper.batchUpdateAuthStatusByIds(AuthStatusEnum.UNAUTHORIZED.getCode(), StatusEnum.DISCONTINUAT.getCode(), idList);


            //写入日志表
            iTrailerAuditLogService.batchInsertLog(idList, AuthStatusEnum.UNAUTHORIZED.getCode());

            idList.forEach(id -> {
                if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
                    WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(null, id);
                    if (Objects.nonNull(weChatVehicle) && !StringUtils.isEmpty(weChatVehicle.getTrailerTypeId()) && weChatVehicle.getAuthStatus() == 0) {
                        String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicle.getTrailerTypeId()).getValue();
                        weChatVehicle.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
                        VehicleDTO vehicleDTO = new VehicleDTO();
                        // 设置车队类型-自有
                        carrierInfoService.toOtmSetFleetType(null,id,weChatVehicle);
                        BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
                        vehicleDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
                        integrationUtil.exportVehicleToOTM(vehicleDTO);
                    }
                }
            });
        } catch (Exception ex) {
            throw new BaseException(-1, ex.getMessage());
        }
    }

    @Override
    public List<Long> selectIdByLspIds(List<Long> lspIdList) {
        return baseMapper.selectIdByLspIds(lspIdList);
    }

    @Override
    public void batchUpdateAuthStatusByIds(Integer authStatus, Integer status, List<Long> idList) {
        baseMapper.batchUpdateAuthStatusByIds(authStatus, status, idList);
    }

    @Override
    public Integer updateCarrier(Long id, Long carrierId) {
        return baseMapper.updateCarrier(id, carrierId);
    }

    @Override
    public Integer batchCarrierNull(List<Long> ids) {
        return baseMapper.batchCarrierNull(ids);
    }

    @Override
    @Transactional
    public Boolean changeLsp(Long[] ids, Long lspId, Integer isAllTransfer, String authorization) throws BaseException {
        if (ids == null || ids.length == 0 || StringUtils.isEmpty(lspId) || StringUtils.isEmpty(isAllTransfer)) {
            throw new BaseException("请选择需要转移的挂车");
        }
        List<Long> trailerIds = Arrays.asList(ids);

        trailerIds.forEach(trailerId -> {
            //中联创建的自有车队  解绑推送erp
            WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(null, trailerId);
            // 业务处理
            LspInfo lspInfo = lspInfoService.selectById(lspId);
            //更新挂车信息
            TrailerInfo trailerInfo = new TrailerInfo();
            trailerInfo.setLspId(lspInfo.getId());
            trailerInfo.setTenantId(lspInfo.getTenantId());
            trailerInfo.setId(trailerId);
            baseMapper.updateLspInfo(trailerInfo);
            trailerInfo = this.selectById(trailerInfo);

            // 删除车队与挂车绑定关系
            fleetBindService.deleteFleetBind(trailerId, TableStatusEnum.STATUS_02.getCode());

            CarrierTrailerBind carrierTrailerBind = new CarrierTrailerBind();
            Wrapper<CarrierTrailerBind> carrierTrailerBindWrapper = new EntityWrapper<>();
            carrierTrailerBindWrapper.eq("trailer_id", trailerId);
            carrierTrailerBind = carrierTrailerBindService.selectOne(carrierTrailerBindWrapper);
            if (isAllTransfer == 1) {
                if (carrierTrailerBind != null) {
                    // 删除车队与牵引车绑定关系
                    fleetBindService.deleteFleetBind(carrierTrailerBind.getCarrierId(), TableStatusEnum.STATUS_01.getCode());
                    carrierTrailerBind.setTenantId(lspInfo.getTenantId());
                    carrierTrailerBindService.update(carrierTrailerBind, carrierTrailerBindWrapper);
                    CarrierTrailerBindLog carrierTrailerBindLog = new CarrierTrailerBindLog();
                    carrierTrailerBindLog.setCarrierId(carrierTrailerBind.getCarrierId());
                    carrierTrailerBindLog.setTenantId(lspInfo.getTenantId());
                    carrierTrailerBindLog.setTrailerId(trailerId);
                    carrierTrailerBindLog.setGmtCreate(new Date());
                    carrierTrailerBindLog.setCreator(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getAccountId()));
                    carrierTrailerBindLogService.insert(carrierTrailerBindLog);
                    //更新牵引车信息
                    CarrierInfo carrierInfo = new CarrierInfo();
                    carrierInfo.setTenantId(lspInfo.getTenantId());
                    carrierInfo.setLspId(lspInfo.getId());
                    carrierInfo.setId(carrierTrailerBind.getCarrierId());
                    carrierInfoService.updateLsp(carrierInfo);
                    carrierInfo = carrierInfoService.selectById(carrierInfo);
                    fleetBindService.deleteFleetBind(carrierInfo.getId(), TableStatusEnum.STATUS_01.getCode());
                    DriverCarrierBind driverCarrierBind = new DriverCarrierBind();
                    Wrapper<DriverCarrierBind> driverCarrierBindWrapper = new EntityWrapper<>();
                    driverCarrierBindWrapper.eq("carrier_id", carrierTrailerBind.getCarrierId());
                    driverCarrierBind = driverCarrierBindService.selectOne(driverCarrierBindWrapper);
                    if (driverCarrierBind != null) {
                        List<DriverCheckin> list = driverCheckinService.selectByNowDayNoTenant(driverCarrierBind.getDriverId());
                        if (!org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                            throw new BaseException("绑定的司机存在报班信息,不能转移");
                        }
                        // 删除车队与司机绑定关系
                        fleetBindService.deleteFleetBind(driverCarrierBind.getDriverId(), TableStatusEnum.STATUS_03.getCode());

                        driverCarrierBind.setTenantId(lspInfo.getTenantId());
                        driverCarrierBindService.update(driverCarrierBind, driverCarrierBindWrapper);
                        //更新司机信息
                        Driver oldDriver = driverService.selectById(driverCarrierBind.getDriverId());
                        Driver driver = new Driver();
                        driver.setId(driverCarrierBind.getDriverId());
                        driver.setTenantId(lspInfo.getTenantId());
                        driver.setLspId(lspInfo.getId());
                        driverService.updateDriverLspRelation(driver);
                        List<NameValuePair> headNamePairs = Lists.newArrayList();
                        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
                        List<NameValuePair> pram = Lists.newArrayList();
                        pram.add(new BasicNameValuePair("DriverId", driver.getId().toString()));
                        String driverWaybill = HttpClientUtil.get(driverWaybillUrl, headNamePairs, pram, socketTimeout);
                        JSONObject driverWaybillJson = JSONObject.parseObject(driverWaybill);
                        if (!Boolean.valueOf(driverWaybillJson.get("data").toString())) {
                            throw new BaseException("司机" + oldDriver.getName() + ":" + "还有未完成的运单");
                        }
                        if (oldDriver.getAccountId() == null) {
                            throw new BaseException("司机:" + oldDriver.getName() + ":" + "账号不存在！");
                        }
                        DriverCarrierBindLog driverCarrierBindLog = new DriverCarrierBindLog();
                        driverCarrierBindLog.setCarrierId(driverCarrierBind.getCarrierId());
                        driverCarrierBindLog.setDriverId(driverCarrierBind.getDriverId());
                        driverCarrierBindLog.setTenantId(lspInfo.getTenantId());
                        driverCarrierBindLog.setGmtCreate(new Date());
                        driverCarrierBindLog.setCreator(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getAccountId()));
                        driverCarrierBindLogService.insert(driverCarrierBindLog);
                        //同步推送更新UAA
                        Map<String, String> prams = new HashMap<>();
                        prams.put("accountId", oldDriver.getAccountId().toString());
                        prams.put("originalTenantId", oldDriver.getTenantId().toString());
                        prams.put("newTenantId", lspInfo.getTenantId().toString());
                        String result = HttpClientUtil.post(uuaUrl + updateTenantOfAccountUrl, headNamePairs, prams, socketTimeout);
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        if (Integer.valueOf(jsonObject.get("code").toString()) != 0) {
                            LOGGER.error("转移更新司机账号 errer :{}", jsonObject.get("message").toString());
                            throw new BaseException("司机:" + driver.getName() + ":" + "更新账号异常！");
                        }
                        //转移牵挂车同时推一遍司机
                        driverService.driverToOtm(driverCarrierBind.getDriverId());
                        //司机信息更新到ERP
                        driverService.authDriverToERP(authorization, driverCarrierBind.getDriverId());
                    }
                    //推送牵引车信息更新到ERP
                    carrierInfoService.carrierToERP(authorization, carrierTrailerBind.getCarrierId());
                }
            } else {
                carrierTrailerBindService.delete(carrierTrailerBindWrapper);
            }
            //推送挂车信息更新到ERP
            trailerInfoService.authTrailerToERP(trailerId, authorization);
            //调整推送OTM
            if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
                if (carrierTrailerBind != null) {
                    //获取中联下面的所有管理员账号
                    EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
                    ew.eq("resource_id", carrierTrailerBind.getCarrierId())
                            .eq("resource_type", TableStatusEnum.STATUS_01.getCode())
                            .orderBy("id", false);
                    List<FleetBindVO> fleetCarrierVOS = fleetBindService.queryBindCarrierList(ew);

                    VehicleDTO vehicleDTO = new VehicleDTO();
                    WeChatVehicle weChatVehicleOTM = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(carrierTrailerBind.getCarrierId(), null);
                    // 设置车队类型-自有
                    carrierInfoService.toOtmSetFleetType(null,trailerId,weChatVehicleOTM);
                    BeanUtils.copyProperties(weChatVehicleOTM, vehicleDTO);
                    if (!CollectionUtils.isEmpty(fleetCarrierVOS)) {
                        vehicleDTO.setFleetId(fleetCarrierVOS.get(0).getFleetId());
                    } else {
                        vehicleDTO.setFleetId(weChatVehicleOTM.getLspId());
                    }
                    vehicleDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
                    if (!StringUtils.isEmpty(weChatVehicleOTM.getTrailerTypeId())) {
                        String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicleOTM.getTrailerTypeId()).getValue();
                        weChatVehicleOTM.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
                    } else {
                        weChatVehicleOTM.setTrailerTypeName("单车");
                        vehicleDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
                    }

                    integrationUtil.exportVehicleToOTM(vehicleDTO);
                }
            }
        });
        return true;
    }

    private void sendOwnInfoToERP(Integer isAllTransfer, String authorization, List<AccountVO> listTenantAccount, WeChatVehicle weChatVehicle, List<FleetBindVO> fleetCarrier) {
        FleetBindVO bindVO = fleetCarrier.get(0);
        Wrapper<FleetLineVO> fleetLineVOWrapper = new EntityWrapper<>();
        fleetLineVOWrapper.eq("id", bindVO.getFleetId());
        List<FleetLineVO> fleetLineVOS = fleetService.queryFleetBindList(fleetLineVOWrapper);
        Wrapper<DriverLicense> driverLicenseWrapper = new EntityWrapper<>();
        driverLicenseWrapper.eq("driver_id", weChatVehicle.getDriverId())
                .orderBy("license_type_id");
        DriverLicense driverLicense = driverLicenseService.selectOne(driverLicenseWrapper);
        TrailerInfo trailerInfo = trailerInfoService.selectById(weChatVehicle.getTrailerId());
        new Thread(() -> {
            for (AccountVO accountVO : listTenantAccount) {
                if (fleetLineVOS.get(0).getCreator().equals(accountVO.getId().toString())
                        && fleetLineVOS.get(0).getFleetTypeId() == 1) {
                    //自有车队--推送到erp
                    List<NameValuePair> headNamePairs = Lists.newArrayList();
                    headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
                    //推送司机
                    DriverToErpDTO driverToErpDTO = new DriverToErpDTO();
                    driverToErpDTO.setId(weChatVehicle.getDriverId());
                    driverToErpDTO.setDriverName(weChatVehicle.getDriverName());
                    driverToErpDTO.setFleetName("");
                    driverToErpDTO.setDriverMobile(weChatVehicle.getDriverMobile());
                    driverToErpDTO.setLspId(weChatVehicle.getLspId() + "");
                    driverToErpDTO.setLspName(weChatVehicle.getLspName());
                    driverToErpDTO.setLicenseId(weChatVehicle.getLicenseId());
                    if (Objects.nonNull(driverLicense)) {
                        driverToErpDTO.setLicenseId(driverLicense.getLicenseId());
                    }
                    LOGGER.info("driverInfoToERP url:{},param:{}", integrationUrl + driverPushErpUrl, JSONObject.toJSONString(driverToErpDTO));
                    String driverResult = null;
                    try {
                        driverResult = HttpClientUtil.postJson(integrationUrl + driverPushErpUrl, headNamePairs, JSONObject.toJSONString(driverToErpDTO), socketTimeout);
                        LOGGER.info("driverInfoToERP---> result {} ", driverResult);
                    } catch (Exception e) {
                        LOGGER.error("driverInfoToERP---> 超时失败 {} ", e);
                    }
                    //推送牵引车
                    CarrierToErpDTO carrierToErpDTO = new CarrierToErpDTO();
                    carrierToErpDTO.setId(weChatVehicle.getId());
                    carrierToErpDTO.setDriverId(weChatVehicle.getDriverId());
                    carrierToErpDTO.setFleetId(null == weChatVehicle.getNewFleetId() ? 0L : weChatVehicle.getNewFleetId());
                    carrierToErpDTO.setTrailerProper(trailerInfo.getTrailerProper());
                    carrierToErpDTO.setTransMode(DictionaryUtil.getTransMode(trailerInfo.getTrailerType()));
                    carrierToErpDTO.setFleetName(weChatVehicle.getFleetName());
                    carrierToErpDTO.setLspId(weChatVehicle.getLspId() + "");
                    carrierToErpDTO.setLspName(weChatVehicle.getLspName());
                    carrierToErpDTO.setDriverName(weChatVehicle.getDriverName());
                    carrierToErpDTO.setDriverPhone(weChatVehicle.getDriverMobile());
                    if (isAllTransfer == 1) {
                        carrierToErpDTO.setTrailerId(weChatVehicle.getTrailerId());
                    } else {
                        carrierToErpDTO.setTrailerId(0L);
                    }
                    carrierToErpDTO.setPlate(weChatVehicle.getPlate());
                    //牵引车增加油卡/路桥卡信息推送erp--油卡
                    EntityWrapper<CarrierCard> oilEW = new EntityWrapper<>();
                    oilEW.eq("carrier_id", weChatVehicle.getId())
                            .eq("card_type_code", TableStatusEnum.STATUS_CARD_100.getCode());
                    List<CarrierCard> oilCards = cardService.selectCardNoTenant(oilEW);
                    if (!CollectionUtils.isEmpty(oilCards)) {
                        carrierToErpDTO.setOilCardNo(oilCards.get(0).getCardSn());
                    }
                    // 路桥卡
                    EntityWrapper<CarrierCard> roadEW = new EntityWrapper<>();
                    roadEW.eq("carrier_id", weChatVehicle.getId())
                            .eq("card_type_code", TableStatusEnum.STATUS_CARD_200.getCode());
                    List<CarrierCard> roadCards = cardService.selectCardNoTenant(roadEW);
                    if (!CollectionUtils.isEmpty(roadCards)) {
                        carrierToErpDTO.setRoadCardNo(roadCards.get(0).getCardSn());
                    }
                    LOGGER.info("CarrierToErp url:{},param:{}", integrationUrl + driverPushErpUrl, JSONObject.toJSONString(carrierToErpDTO));
                    String carResult = null;
                    try {
                        carResult = HttpClientUtil.postJson(integrationUrl + carrierPushErpUrl, headNamePairs, JSONObject.toJSONString(carrierToErpDTO), socketTimeout);
                        LOGGER.info("CarrierToErp result {} ", carResult);
                    } catch (Exception e) {
                        LOGGER.error("CarrierToErp 超时失败 {} ", e);
                    }
                    //推送挂车
                    TrailerToErpDTO trailerToErpDTO = new TrailerToErpDTO();
                    trailerToErpDTO.setId(weChatVehicle.getTrailerId());
                    trailerToErpDTO.setTrailerPlate(weChatVehicle.getTrailerPlate());
                    if (Objects.nonNull(trailerInfo.getAxisNumber())) {
                        trailerToErpDTO.setAxisNumber(trailerInfo.getAxisNumber());
                    }
                    LOGGER.info("TrailerToErp url:{},param:{}", integrationUrl + driverPushErpUrl, JSONObject.toJSONString(trailerToErpDTO));
                    String trResult = null;
                    try {
                        trResult = HttpClientUtil.postJson(integrationUrl + trailerPushErpUrl, headNamePairs, JSONObject.toJSONString(trailerToErpDTO), socketTimeout);
                        LOGGER.info("TrailerToErp result {} ", trResult);
                    } catch (Exception e) {
                        LOGGER.error("TrailerToErp 超时失败: {} ", e);
                    }
                }
            }
        }).start();
    }


    @Override
    public List<TrailerCarrierBO> listUsableTrailer(Wrapper<TrailerCarrierBO> ew) {
        return baseMapper.listUsableTrailer(ew);
    }

    //判断证照有效性
    private Integer getValidStatus(TrailerLicense trailerLicense, Boolean isHaveAttach) {
        if (Objects.isNull(isHaveAttach)) {
            // 查找证照的附件信息
            Wrapper<TrailerLicenseAttach> ew = new EntityWrapper<>();
            ew.eq("license_id", trailerLicense.getId()).eq("trailer_id", trailerLicense.getId());
            List<TrailerLicenseAttach> lspLicenseAttachList = trailerLicenseAttachService.selectList(ew);
            if (!CollectionUtils.isEmpty(lspLicenseAttachList)) {
                isHaveAttach = true;
            }
        }

        // 根据时间
        if (Objects.nonNull(trailerLicense.getGmtReg()) && Objects.nonNull(trailerLicense.getGmtOverdue()) && isHaveAttach &&
                trailerLicense.getGmtOverdue().compareTo(trailerLicense.getGmtReg()) >= 0 && trailerLicense.getGmtOverdue().compareTo(new Date()) >= 0
                && !StringUtils.isEmpty(trailerLicense.getLicenseId())) {
            return LicenseStatusEnum.VALID.getCode();
        } else {
            return LicenseStatusEnum.INVALID.getCode();
        }
    }

    @Override
    public List<String> deleteByIds(Long[] trailerIds) {
        List<String> msgs = new ArrayList<>();
        for (Long id : trailerIds) {
            String msg = "";
            TrailerInfo trailer = this.selectById(id);
            if (AuthStatusEnum.CERTIFICATION.getCode().equals(trailer.getAuthStatus())) {
                msg = "挂车:" + trailer.getPlate() + ":已认证无法删除";
                msgs.add(msg);
                continue;
            }

            Wrapper<CarrierTrailerBind> ewBind = new EntityWrapper<>();
            ewBind.eq("trailer_id", id);
            if (carrierTrailerBindService.selectCount(ewBind) > 0) {
                msg = "挂车:" + trailer.getPlate() + ":已经与牵引车绑定，无法删除";
                msgs.add(msg);
                continue;
            }
            this.deleteById(id);
        }

        return msgs;
    }


    @Override
    public String getTrailerInfoByDriverAndCarrier(Long driverId, String plate) throws BaseException {
        carrierInfoService.verifyCarrier(driverId, plate);
        String strPlate = getTrailerInfoByCarrier(plate);
        return strPlate;
    }


    @Override
    public Boolean verifyTrailerInfoByCarrier(Long driverId, String plate, String tailerPlate) throws BaseException {
        return verifyTrailer(driverId, plate, tailerPlate);
    }

    @Override
    public TrailerInfoBO selectByCarrierInfoId(Long carrierInfoId) {
        return baseMapper.selectByCarrierInfoId(carrierInfoId);
    }

    /**
     * 得到挂车车牌
     *
     * @param plate
     * @return
     */
    private String getTrailerInfoByCarrier(String plate) {
        String strTrailerPlate = null;
        EntityWrapper<CarrierInfo> ewCarrierInfo = new EntityWrapper<>();
        ewCarrierInfo.eq("plate", plate);
        CarrierInfo carrierInfo = carrierInfoService.selectOne(ewCarrierInfo);
        if (Objects.nonNull(carrierInfo)) {
            TrailerInfoBO trailerInfoBO = baseMapper.selectByCarrierInfoId(carrierInfo.getId());
            if (Objects.nonNull(trailerInfoBO)) {
                strTrailerPlate = trailerInfoBO.getPlate();
            }
        }
        return strTrailerPlate;
    }


    /**
     * 挂车完善信息状态
     */
    public Boolean getTrailerStatus(Long trailerId, String typeCode, String subjectCode) {
        Boolean blnTrailerStatus = true;
        //判断证照信息
        LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(typeCode, subjectCode);
        if (Objects.isNull(licenseTypeBO)) {
            throw new BaseException("缺少证照类型");
        }
        EntityWrapper<TrailerLicense> ewdl = new EntityWrapper<>();
        ewdl.eq("license_type_id", licenseTypeBO.getId());
        ewdl.eq("trailer_id", trailerId);
        List<TrailerLicense> dls = trailerLicenseService.selectList(ewdl);
        if (!org.apache.commons.collections4.CollectionUtils.isEmpty(dls)) {
            TrailerLicense trailerLicense = dls.get(0);
            TrailerLicenseBO vehicleLicenseBO = new TrailerLicenseBO();
            BeanUtils.copyProperties(trailerLicense, vehicleLicenseBO);
            if (Objects.nonNull(vehicleLicenseBO.getId())) {
                EntityWrapper<TrailerLicenseAttach> ew = new EntityWrapper<>();
                ew.eq("trailer_id", trailerId).eq("license_id", vehicleLicenseBO.getId());
                List<TrailerLicenseAttach> trailerLicenseAttachs = trailerLicenseAttachService.selectList(ew);
                if (!CollectionUtils.isEmpty(trailerLicenseAttachs)) {
                    blnTrailerStatus = true;
                }
            } else {
                blnTrailerStatus = false;
            }

        }
        return blnTrailerStatus;
    }

    /**
     * 校验挂车
     */
    private Boolean verifyTrailer(Long driverId, String plate, String tailerPlate) throws BaseException {
        CarrierInfo carrierInfo = null;

        //判断司机的认证状态
        Driver driver = driverService.selectById(driverId);
        if (Objects.isNull(driver)) {
            throw new BaseException("司机信息不存在");
        }

        //根据车牌号得到牵引车信息 由于牵引车已经校验，所以牵引车无需做校验
        EntityWrapper<CarrierInfo> carrierInfoEntityWrapper = new EntityWrapper<>();
        carrierInfoEntityWrapper.eq("plate", plate);
        List<CarrierInfo> carrierInfoList = carrierInfoService.selectCarrierListNoTenant(carrierInfoEntityWrapper);
        if (!org.apache.commons.collections4.CollectionUtils.isEmpty(carrierInfoList)) {
            carrierInfo = carrierInfoList.get(0);
        }

        //司机在“未认证”状态下，绑定的牵引车和挂车车牌，不能为已在库的车牌
        if (driver.getAuthStatus().equals(AuthStatusEnum.UNAUTHORIZED.getCode())) {
            //根据车牌号得到牵引车信息
            EntityWrapper<TrailerInfo> trailerInfoEntityWrapper = new EntityWrapper<>();
            trailerInfoEntityWrapper.eq("plate", tailerPlate);
            List<TrailerInfo> trailerInfoList = baseMapper.selectTrailerNoTenant(trailerInfoEntityWrapper);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(trailerInfoList)) {
                throw new BaseException("该挂车已锁定，无法在进行绑定！");
            }
        }

        //司机在“已认证”状态下，可以选择已在库并且“已认证”的牵引车，若该牵引车当前已绑定挂车，则自动带出挂车信息，司机不得修改挂车信息；若该牵引车当前未绑定挂车，司机可录入新挂车，也可选择在库且未绑定牵引车的挂车。
        if (driver.getAuthStatus().equals(AuthStatusEnum.CERTIFICATION.getCode())) {
            //根据车牌号得到牵引车信息
            EntityWrapper<TrailerInfo> trailerInfoEntityWrapper = new EntityWrapper<>();
            trailerInfoEntityWrapper.eq("plate", tailerPlate);
            List<TrailerInfo> trailerInfoList = baseMapper.selectTrailerNoTenant(trailerInfoEntityWrapper);

            //如果是已经在库的挂车
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(trailerInfoList)) {
                //判断的逻辑：不能绑定其他承运商的车；不能绑定已绑定其他司机的车；当前已认证的司机不能绑定未认证的车
                TrailerInfo trailerInfo = trailerInfoList.get(0);
                //不能绑定其他承运商的挂车；
                Long lspId = driver.getLspId();
                if (!trailerInfo.getLspId().equals(lspId)) {
                    throw new BaseException("该挂车属于其他承运商，无法进行绑定！");
                }
                //不能绑定已绑定其他牵引车的挂车；
                Long trailerId = trailerInfo.getId();
                if (Objects.nonNull(carrierInfo)) {
                    CarrierTrailerBind carrierTrailerBind = carrierTrailerBindService.getCarrierTrailerBindByTrailIdNoCId(trailerId, carrierInfo.getId());
                    if (Objects.nonNull(carrierTrailerBind)) {
                        throw new BaseException("该挂车已经绑定其他牵引车，无法进行绑定！");
                    }
                }
            }
        }
        return true;
    }

    /**
     * 添加trailer
     */
    private TrailerInfo addTrailerByCarrier(String trailerPlate, Driver driver, CarrierInfo carrierInfo) {
        TrailerInfo trailerInfo = null;

        JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
        //先判断库里是否存在已存在挂车
        EntityWrapper<TrailerInfo> trailerInfoEntityWrapper = new EntityWrapper<>();
        trailerInfoEntityWrapper.eq("plate", trailerPlate);
        List<TrailerInfo> trailerInfoList = this.selectList(trailerInfoEntityWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(trailerInfoList)) {
            trailerInfo = trailerInfoList.get(0);
        } else {
            //不在库则新建
            trailerInfo = new TrailerInfo();
            trailerInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
            trailerInfo.setLspId(driver.getLspId());
            trailerInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
            trailerInfo.setCreateFrom(SourceEnum.WEIXIN.getText());
            trailerInfo.setCreator(jwtAccount.getUsername());
            trailerInfo.setPlate(trailerPlate);
            trailerInfo.setTenantId(driver.getTenantId());
            this.insert(trailerInfo);
        }

        //判断牵引车和挂车是否已经是是绑定关系，如果不是，则进行校验
        CarrierTrailerBind carrierTrailerBind = carrierTrailerBindService.getCarrierTrailerBindByTIdAndCId(trailerInfo.getId(), carrierInfo.getId());
        if (Objects.isNull(carrierTrailerBind)) {
            //新建绑定关系
            carrierTrailerBind = new CarrierTrailerBind();
            carrierTrailerBind.setCarrierId(carrierInfo.getId());
            carrierTrailerBind.setTrailerId(trailerInfo.getId());
            carrierTrailerBind.setGmtCreate(new Date());
            carrierTrailerBindService.insert(carrierTrailerBind);
            //编写绑定关系的日志
            CarrierTrailerBindLog log = new CarrierTrailerBindLog();
            log.setCarrierId(carrierInfo.getId());
            log.setTrailerId(trailerInfo.getId());
            log.setGmtCreate(new Date());
            carrierTrailerBindLogService.insert(log);
        }

        return trailerInfo;
    }

    /**
     * 更新挂车信息
     */
    @Override
    @Transactional
    public TrailerInfo updateTrailer(TrailerInfo trailerInfo) {
        try {
            if (!Strings.isNullOrEmpty(trailerInfo.getOwnerName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, trailerInfo.getOwnerName()))
                    throw new BaseException("车主姓名不合法");
            if (!Strings.isNullOrEmpty(trailerInfo.getManufacturer()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, trailerInfo.getManufacturer()))
                    throw new BaseException("生产厂商不合法");
            if (!Strings.isNullOrEmpty(trailerInfo.getModel()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, trailerInfo.getModel()))
                    throw new BaseException("品牌车型不合法");
            if (StringUtils.isEmpty(trailerInfo.getPlate())) {
                throw new BaseException("挂车车牌不能为空");
            } else if (!trailerInfo.getPlate().endsWith("挂")) {
                throw new BaseException("挂车车牌号不正确:XXX挂");
            }
            TrailerInfo planExistTailer = this.getPlanExistTailer(trailerInfo);
            if (Objects.nonNull(planExistTailer))
                throw new BaseException(CarrierEnum.PLATE_EXIST.getCode(), "该车牌号已被使用");
            if (Objects.isNull(trailerInfo.getLspId())) throw new BaseException("未选择承运商");
            LspInfo lspInfo = lspInfoService.selectById(trailerInfo.getLspId());
            if (Objects.nonNull(lspInfo.getId())) {
                trailerInfo.setLspId(lspInfo.getId());
                trailerInfo.setTenantId(lspInfo.getTenantId());
            }
            // 添加挂车基础信息
            if (Objects.isNull(trailerInfo.getId())) {
                JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
                trailerInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                trailerInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
                trailerInfo.setCreateFrom(SourceEnum.LSPM.getText());
                if (Objects.nonNull(jwtAccount)) {
                    trailerInfo.setCreator(jwtAccount.getAccountId());
                }
                trailerInfo.setGmtCreate(new Date());
                this.insert(trailerInfo);
            } else {
                trailerInfo.setGmtUpdate(new Date());
                this.updateById(trailerInfo);
            }
            return trailerInfo;
        } catch (BaseException e) {
            throw e;
        } catch (Exception ex) {
            throw new BaseException(-1, "操作异常请重试");
        }

    }

    /**
     * 获取挂车信息
     */
    @Override
    public TrailerBasicVO getTrailerInfoLine(Long trailerId) {
        TrailerBasicVO trailerInfoLineVO = new TrailerBasicVO();
        if (Objects.isNull(trailerId)) throw new BaseException("请传入挂车信息");
        EntityWrapper<TrailerInfo> driverEntityWrapper = new EntityWrapper<>();
        driverEntityWrapper.eq("id", trailerId);
        List<TrailerInfo> trailerInfos = baseMapper.selectTrailerNoTenant(driverEntityWrapper);
        TrailerInfo trailerInfo = trailerInfos.get(0);
        if (Objects.isNull(trailerInfo)) throw new BaseException("未找到对应挂车信息");
        BeanUtils.copyProperties(trailerInfo, trailerInfoLineVO);
        // 拿车队ID查询车队名
        if (Objects.nonNull(trailerInfo.getFleetId())) {
            Fleet fleet = fleetService.selectByIdNoTenant(trailerInfo.getFleetId());
            if (Objects.nonNull(fleet)) {
                trailerInfoLineVO.setFleetName(fleet.getFleetName());
            }
        }
        if (Objects.nonNull(trailerInfo.getLspId())) {
            LspInfo lspInfo = lspInfoService.selectById(trailerInfo.getLspId());
            if (lspInfo != null) {
                trailerInfoLineVO.setLspName(lspInfo.getName());
            }
        }
        if (Objects.nonNull(trailerInfo.getTrailerType())) {
            List<TransportationTypeVO> allServiceType = mdmUtil.getAllFleetTransportType();
            String serviceTypeName = trailerInfo.getTrailerType();
            for (TransportationTypeVO transportationTypeVO :
                    allServiceType) {
                serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
            }
            trailerInfoLineVO.setTrailerTypeName(serviceTypeName);
        }
        return trailerInfoLineVO;
    }

    /**
     * 根据车牌获取挂车信息
     */
    private TrailerInfo getPlanExistTailer(TrailerInfo trailerInfo) {
        Wrapper<TrailerInfo> mobileDriverEntity = new EntityWrapper<>();
        mobileDriverEntity.eq("plate", trailerInfo.getPlate().trim())
                .ne("is_delete", TableStatusEnum.STATUS_1.getCode());
        if (Objects.nonNull(trailerInfo.getId())) {
            mobileDriverEntity.ne("id", trailerInfo.getId());
        }
        List<TrailerInfo> trialerList = baseMapper.selectTrailerNoTenant(mobileDriverEntity);
        if (!CollectionUtils.isEmpty(trialerList)) {
            return trialerList.get(0);
        }
        return null;
    }

    @Override
    public Page<TrailerCarrierBO> carrierTrailerList(Page<TrailerCarrierBO> page) {
        Map<String, Object> condition = page.getCondition();
        Wrapper<TrailerCarrierBO> ew = buildCarTraCondition(condition);
        List<TrailerCarrierBO> carrierTrailerBOS = baseMapper.TrailerCarrierList(page, ew);
        carrierTrailerBOS.forEach(trailerCarrierBO -> {
            if (Objects.nonNull(trailerCarrierBO.getTrailerType())) {
                List<TransportationTypeVO> allServiceType = mdmUtil.getAllFleetTransportType();
                String serviceTypeName = trailerCarrierBO.getTrailerType();
                for (TransportationTypeVO transportationTypeVO :
                        allServiceType) {
                    serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
                }
                trailerCarrierBO.setTrailerTypeName(serviceTypeName);
                if (Objects.nonNull(trailerCarrierBO.getTractorType())) {
                    if (TractorTypeEnum.TRACTORVEHICLE.getCode().toString().equals(trailerCarrierBO.getTractorType()))
                        trailerCarrierBO.setTractorTypeName(TractorTypeEnum.TRACTORVEHICLE.getText());
                    if (TractorTypeEnum.RECOVERYVEHICLE.getCode().toString().equals(trailerCarrierBO.getTractorType()))
                        trailerCarrierBO.setTractorTypeName(TractorTypeEnum.RECOVERYVEHICLE.getText());
                }
            }
        });
        page.setRecords(carrierTrailerBOS);
        return page;
    }

    private Wrapper<TrailerCarrierBO> buildCarTraCondition(Map<String, Object> condition) {
        Wrapper<TrailerCarrierBO> ew = new EntityWrapper<>();
        if (!Objects.isNull(condition)) {
            //司机名
            if (condition.containsKey("driverName") && !StringUtils.isEmpty(condition.get("driverName"))) {
                ew.like("driverName", condition.get("driverName").toString().trim());
            }
            //挂车车牌
            if (condition.containsKey("trailerPlate") && !StringUtils.isEmpty(condition.get("trailerPlate"))) {
                ew.like("trailerPlate", condition.get("trailerPlate").toString().trim());
            }
        }
        ew.orderBy("gmt_create", false);
        return ew;

    }

    @Override
    public void updateLspInfo(TrailerInfo trailerInfo) {
        baseMapper.updateLspInfo(trailerInfo);
    }

    @Override
    public List<String> updateDeleteStatus(List<Long> ids) {
        try {
            List<String> msgs = new ArrayList<>();
            if (CollectionUtils.isEmpty(ids)) throw new BaseException("请选择恢复删除的挂车");
            for (Long id : ids) {
                String msg = "";
                EntityWrapper<TrailerInfo> trailerInfoEntityWrapper = new EntityWrapper<>();
                trailerInfoEntityWrapper.eq("id", id);
                List<TrailerInfo> trailerInfos = baseMapper.selectTrailerNoTenant(trailerInfoEntityWrapper);
                TrailerInfo trailerInfo = trailerInfos.get(0);
                if (Objects.isNull(trailerInfo)) {
                    msg = "挂车:" + trailerInfo.getPlate() + ":挂车不存在";
                    msgs.add(msg);
                    continue;
                }
                baseMapper.updateDeleteStatus(trailerInfoEntityWrapper);
            }
            return msgs;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("恢复失败");
        }
    }

    @Override
    public List<TrailerInfo> selectListNoTenant(EntityWrapper<TrailerInfo> tlEW) {
        return baseMapper.selectListNoTenant(tlEW);
    }

    @Override
    public TrailerInfo selectByIdNoTenant(Long trailerId) {
        return baseMapper.selectByIdNoTenant(trailerId);
    }
}

